import { JSEncrypt } from 'jsencrypt';
import { defineStore } from 'pinia';

import { accountLogin, getPKey } from '@/api/login/index';
import router from '@/router';
import { usePermissionStore } from '@/store';

interface loginParams {
  username: string;
  password: string;
  code: string;
  remember: boolean;
  way: string;
}

interface RememberInfo {
  username: string;
  password: string;
}

interface Info {
  id: string;
  account: string;
  userId: string;
  token: string;
  cmpId: string;
  orgId: string;
  cmpName: string;
  orgName: string;
  fullName: string;
}

interface State {
  info: Info | {};
  token: string;
  rememberInfo: RememberInfo[];
  name: string; // 用户名，用于展示在页面右上角头像处
  roles: string[]; // 前端权限模型使用 如果使用请配置modules/permission-fe.ts使用
}

export const useUserStore = defineStore('userStore', {
  state: (): State => {
    return {
      token: '',
      info: {},
      rememberInfo: [],
      name: '', // 用户名，用于展示在页面右上角头像处
      roles: [], // 前端权限模型使用 如果使用请配置modules/permission-fe.ts使用
    };
  },
  actions: {
    /**
     * 登录
     * @param form 表单数据
     */
    async login(form: loginParams) {
      // 获取公钥
      const publickey = await getPKey();
      const encrypt = new JSEncrypt();
      encrypt.setPublicKey(publickey);
      // 加密用户名和密码
      const username = encrypt.encrypt(form.username) as string;
      const password = encrypt.encrypt(form.password) as string;
      // 定义参数
      const params = {
        code: form.code,
        username,
        password,
        way: form.way,
      };
      // 调用接口
      try {
        const data = await accountLogin(params);
        // 保存用户信息
        this.token = data.token;
        this.info = data;
        // 保存当前账号密码
        if (form.remember) {
          const { username, password } = form;
          this.setRememberInfo({ username, password });
        }
        const permissionStore = usePermissionStore();
        // await permissionStore.initRoutes();
        await permissionStore.buildAsyncRoutes();
        // 跳转页面
        router.push('/dashboard/base');
        return Promise.resolve();
      } catch (error) {
        return Promise.reject(new Error('登录失败，请刷新验证码后重新登录'));
      }
    },
    /**
     * 退出登录
     */
    async logout() {
      this.$reset();
    },
    /**
     * 更新账号密码组
     * @param rememberInfo 当前账号密码
     */
    setRememberInfo(rememberInfo: RememberInfo) {
      this.rememberInfo.forEach((item, index) => {
        if (item.username === rememberInfo.username) {
          this.rememberInfo.splice(index, 1);
        }
      });
      this.rememberInfo.push(rememberInfo);
    },
  },
  persist: true,
});
